<template>
  <div>
    <el-form label-width="100px">
      <el-form-item label="文章标题">
        <el-input v-model="form.title" :placeholder="form.title"></el-input>
      </el-form-item>
      <el-form-item label="文章内容">
        <div id="div1"></div> </el-form-item
      ><el-form-item label="文章来源">
        <el-input
          v-model="form.stemfrom"
          :placeholder="form.stemfrom"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="concelForm">取消</el-button>
        <el-button type="primary" @click="submitForm">修改</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from "vue";
import { useRouter, useRoute } from "vue-router";
import { http } from "../../utils/http";
import E from "wangeditor";
import { useStore } from "vuex";
import { ElMessage } from 'element-plus'
const store = useStore()
const router = useRouter()
const route = useRoute()
let form = reactive({
  id: 0,
  createTime: "",
  title: "",
  stemfrom: "",
  content: "",
  author: store.state.msg.username,
});

let editor = ref(null)
onMounted( async  () => {
  let beforeArticle = await http.get(`/article/findOne?id=${ route.query.id }`)
  form.id = beforeArticle.data.id
  form.createTime = beforeArticle.data.createTime
  form.title = beforeArticle.data.title
  form.stemfrom = beforeArticle.data.stemfrom
  form.content = beforeArticle.data.content
  form.author = beforeArticle.data.author
  editor = new E("#div1");
  editor.config.uploadImgServer = `http://192.168.0.222:3001/article/upload`
  editor.config.uploadFileName = 'img'
  editor.config.uploadImgHeaders = {
    authorization: "Bearer " + localStorage.getItem('token')
  }
  editor.config.height = 600
  editor.create();
  // 创建之后才能回填内容
  editor.txt.html(beforeArticle.data.content)
})

// 取消编辑
const concelForm = () => {
  router.go(-1)
}
// 确定修改
const submitForm = async () => {
  let date = new Date();
  form.createTime = date.getTime();
  form.content = editor.txt.html()
  try{
    let res = await http.post('/article/update', form)
    if( res.code === 200 ){
      router.push({
        path:'/admin/article'
      })
      ElMessage.success({
        type:'success',
        message: '修改成功'
      })
    }else{
      ElMessage.error({
        type:'error',
        message: '修改失败'
      })
    }
  }catch( err ){
    console.log(err);
  }
}
</script>

<style lang="scss" scoped>
.el-form {
  width: 70%;
  margin: 0 auto ;
  div:last-child {
    div {
      button:nth-child(1) {
        position: absolute;
        left: 45%;
        transform: translateX(-50%);
      }
      button:nth-child(2) {
        position: absolute;
        left: 55%;
        transform: translateX(-50%);
      }
    }
  }
}
</style>